package com.linrung.sf.datastat;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.linrung.platform.job.jobConfig.JobConfigEntity;
import com.linrung.scheduler.core.AbstractJobBusinessService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Year;
import java.util.*;

/**
 * 统计提前处理
 * @author 545
 */
@Service("DataStatService")
public class DataStatService extends AbstractJobBusinessService {

    private static Logger logger = Logger.getLogger(DataStatService.class);

    @Autowired
    @Qualifier("jdbcTemplate")
    private JdbcTemplate jdbcTemplate;


    @Override
    public String execute(JobConfigEntity jc) {
        //0 50 23 ? * SUN ?         每周日凌晨9点检测生成数据
        //0 50 11 ? * SUN           每周日凌晨9点检测生成数据
        //0 0 9,11 * * ?             每天9点或11点
        Map<String, String> config = jc.getParams();
        int pageSize = 100;
        if(config.containsKey("PAGE_SIZE")){
            pageSize = Convert.toInt(config.get("PAGE_SIZE"));
        }

        try{
            logger.info("开始生成重点用户本周最新状态.....");
            startGenPopulation(pageSize);
            logger.info("生成重点用户本周最新状态结束.....");
        }catch (Exception e){
            logger.error("获取用户数据发生错误：", e);
        }

        return null;
    }

    /**
     * 保存重点人员在每一周最后的状态。
     * @param pageSize
     */
    private void startGenPopulation(int pageSize){

        Date now = DateUtil.date();
        int year = DateUtil.year(now);
        int month = DateUtil.month(now) + 1;
        int week = DateUtil.weekOfMonth(now);

        //检测本周是否已有生成数据
        String testSql = "SELECT COUNT(*) FROM LR_DGS_POPULATION_STATUS T WHERE T.D_YEAR = ? AND T.D_MONTH = ? AND T.D_WEEK = ?";
        boolean isGenWeekData = false;
        long count = this.jdbcTemplate.queryForObject(testSql, new Object[]{year, month, week}, Long.class);
        if(count > 0){
            isGenWeekData = true;   //本周生成
        }

        if(!isGenWeekData){
            String totalSql = "SELECT COUNT(*) FROM LR_DGS_POPULATION WHERE IS_IMPORTANT = 1 AND DATA_STATE = 1";
            long totalCount = this.jdbcTemplate.queryForObject(totalSql, Long.class);
            if(totalCount <= 0){
                return;
            }

            long i=0;
            do{
                List<Map<String, Object>> list = loadPopulationList(i, pageSize);
                genTodoItems(list, year, month, week);

                i += pageSize;
            }while(i<totalCount);
        }
    }



    public void genTodoItems(List<Map<String, Object>> list, int year, int month, int week) {
        if(list.isEmpty()){
            return;
        }

        String insert = "insert into LR_DGS_POPULATION_STATUS(ID,POP_ID,GRID_ID,POP_TYPE,POP_CER_TYPE,IS_IMPORTANT,DATA_STATE,IMPORTANT_TYPE,POP_STATUS,CHECK_STATE,D_YEAR,D_MONTH,D_WEEK) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
        jdbcTemplate.batchUpdate(insert, new BatchPreparedStatementSetter() {
            @Override
            public int getBatchSize() {
                return list.size();
            }
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                Map<String, Object> data = list.get(i);
                ps.setString(1, IdUtil.simpleUUID());
                ps.setString(2, (String) data.getOrDefault("ID", null));
                ps.setString(3, (String) data.getOrDefault("GRID_ID", null));
                ps.setBigDecimal(4, (BigDecimal) data.getOrDefault("POP_TYPE", null));
                ps.setBigDecimal(5, (BigDecimal) data.getOrDefault("POP_CER_TYPE", null));
                ps.setBigDecimal(6, (BigDecimal) data.getOrDefault("IS_IMPORTANT", null));
                ps.setBigDecimal(7, (BigDecimal) data.getOrDefault("DATA_STATE", null));

                String importantType = (String) data.getOrDefault("IMPORTANT_TYPE", null);
                if(StringUtils.isNotBlank(importantType)){
                    importantType = ",".concat(importantType).concat(",");
                }
                ps.setString(8, importantType);
                ps.setBigDecimal(9, (BigDecimal) data.getOrDefault("POP_STATUS", null));
                ps.setBigDecimal(10, (BigDecimal) data.getOrDefault("CHECK_STATE", null));
                ps.setInt(11, year);
                ps.setInt(12, month);
                ps.setInt(13, week);
            }
        });
    }

    /**
     * 查找符合条件的重点人员
     * @param i
     * @param pageSize
     * @return
     */
    public List<Map<String, Object>> loadPopulationList(long i, int pageSize){
        String msgSql = "SELECT * FROM (select a.ID,a.GRID_ID,a.POP_TYPE,a.POP_CER_TYPE,a.IS_IMPORTANT,a.DATA_STATE,a.IMPORTANT_TYPE,a.POP_STATUS,a.CHECK_STATE,ROWNUM as RN from LR_DGS_POPULATION a where a.IS_IMPORTANT = 1 AND a.DATA_STATE = 1) where RN > ? AND RN <= ?";
        return this.jdbcTemplate.queryForList(msgSql, i, i+pageSize);
    }


}
